package com.easytouch.vmhdl.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.widget.TextView;

import com.easytouch.core.DriverThread;
import com.easytouch.core.listener.OnDoorStateChangedListener;
import com.easytouch.core.model.ColumnModel;
import com.easytouch.core.utils.Log;
import com.easytouch.vmhdl.AppApplication;
import com.easytouch.vmhdl.R;
import com.easytouch.vmhdl.fragment.AddFragment;
import com.easytouch.vmhdl.fragment.BaseMgrFragment;
import com.easytouch.vmhdl.fragment.ConfigFragment;
import com.easytouch.vmhdl.fragment.MenuFragment;
import com.easytouch.vmhdl.fragment.TestFragment;
import com.easytouch.vmhdl.fragment.UpdateFragment;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by gulin on 2018/1/9.
 */

public class ManagerActivity extends FragmentActivity implements OnDoorStateChangedListener {

    public static final int FRAGMENT_MENU = 0;
    public static final int FRAGMENT_ADD = 1;
    public static final int FRAGMENT_CONFIG = 2;
    public static final int FRAGMENT_WARRANTY = 3;
    public static final int FRAGMENT_TEST = 4;
    public static final int FRAGMENT_UPDATE = 5;

    private Log mLogger = new Log("ManagerActivity.txt");

    public static final String FILE_MAX_CONFIG_DIR = AppApplication.path + "/data";
    public static final String FILE_MAX_CONFIG_NAME = "maxaddconfig.txt";
    public static final String FILE_MAX_CONFIG = FILE_MAX_CONFIG_DIR + "/" + FILE_MAX_CONFIG_NAME;

    FragmentManager mFragmentManager;
    private BaseMgrFragment mFragment;

    private TextView mTvTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manager);

        mFragmentManager = getSupportFragmentManager();
        mFragment = new MenuFragment();
        mFragmentManager.beginTransaction().replace(R.id.fl_content, mFragment).commit();

        mTvTitle = findViewById(R.id.tv_title);

        DriverThread.getInstance().setOnDoorStateChangedListener(this);
    }

    public void goFragment(final int toFragment, final Bundle bundle)
    {
        BaseMgrFragment fragment = null;
        switch (toFragment)
        {
            case FRAGMENT_MENU:
                fragment = new MenuFragment();
                break;
            case FRAGMENT_ADD:
                fragment = new AddFragment();
                break;
            case FRAGMENT_CONFIG:
                fragment = new ConfigFragment();
                break;
            case FRAGMENT_WARRANTY:
                break;
            case FRAGMENT_TEST:
                fragment = new TestFragment();
                break;
            case FRAGMENT_UPDATE:
                fragment = new UpdateFragment();
                break;
            default:
                return;
        }
        if(fragment != null)
        {
            mFragment = fragment;
        }
        else
        {
            mFragment = null;
            return;
        }
        FragmentTransaction ft = mFragmentManager.beginTransaction();
        if(bundle != null)
        {
            fragment.setArguments(bundle);
        }
        ft.replace(R.id.fl_content, fragment);
        ft.commitAllowingStateLoss();
    }

    public void setTitle(final int pResId)
    {
        mTvTitle.setText(pResId);
    }

    public static void readMaxConfig(final String pFileName, final boolean isModifyGoods)
    {
        File file = new File(pFileName);
        if(!file.exists()) //文件不存在
        {
            //使用一些默认的数值
            for (int i = 1;i <= 11;i++)
            {
                if(DriverThread.getInstance().mRoadInfo.containsKey(i))
                {
                    ColumnModel[] columnArray = DriverThread.getInstance().mRoadInfo.get(i);
                    for (ColumnModel model: columnArray) {
                        if(i >= 1 && i <= 5) //商品柜
                        {
                            model.maxStock = 1;
                        }
                        else if(i >= 6 && i <= 9) //食品机
                        {
                            model.maxStock = model.num > 10 ? model.num : 10; //当前库存如果大于10就使用当前库存来当做容量
                        }
                        else //饮料机
                        {
                            model.maxStock = 20;
                        }
                    }
                }
            }
            ManagerActivity.saveMaxConfig();
        }
        else //读取文件
        {
            ConcurrentHashMap<Integer, ColumnModel[]> roadInfo = null;
            FileInputStream fis = null;
            ObjectInputStream ois = null;
            try
            {
                fis = new FileInputStream(file);
                ois = new ObjectInputStream(fis);
                roadInfo = (ConcurrentHashMap<Integer, ColumnModel[]>)ois.readObject();
            }
            catch(IOException e)
            {
                //logger.e("read max config IOException:" + e.getMessage());
            }
            catch (ClassNotFoundException e)
            {
                //logger.e("read max config ClassNotFoundException:" + e.getMessage());
            }
            finally
            {
                try
                {
                    if(ois != null)
                    {
                        ois.close();
                    }
                    if(fis != null)
                    {
                        fis.close();
                    }
                }
                catch(IOException e)
                {
                    //logger.e("close file IOException:" + e.getMessage());
                }
            }
            //获取最大补货量
            if(roadInfo == null)
                return;
            for (int i = 1;i <= 11;i++)
            {
                if(DriverThread.getInstance().mRoadInfo.containsKey(i) && roadInfo.containsKey(i))
                {
                    ColumnModel[] columnArray = DriverThread.getInstance().mRoadInfo.get(i);
                    ColumnModel[] columnArray2 = roadInfo.get(i);
                    for (int j = 0;j < columnArray.length;j++)
                    {
                        if(j < columnArray2.length)
                        {
                            columnArray[j].maxStock = columnArray2[j].maxStock;
                            if(isModifyGoods)
                            {
                                columnArray[j].goodsId = columnArray2[j].goodsId;
                                columnArray[j].price = columnArray2[j].price;
                            }
                        }
                    }
                }
            }
        }
    }

    public static void saveMaxConfig()
    {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        File file = new File(FILE_MAX_CONFIG_DIR);
        try
        {
            if(!file.exists())
            {
                file.mkdirs();
            }
            file = new File(FILE_MAX_CONFIG);
            if(!file.exists())
            {
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(DriverThread.getInstance().mRoadInfo);
        }
        catch(IOException e)
        {
            //logger.e("write max config IOException:" + e.getMessage());
        }
        finally
        {
            try
            {
                if(oos != null)
                {
                    oos.close();
                }
                if(fos != null)
                {
                    fos.close();
                }
            }
            catch(IOException e)
            {
                //logger.e("close file IOException:" + e.getMessage());
            }
        }
    }

    public void cleanUp()
    {
        DriverThread.getInstance().removeOnDoorStateChangedListener();
    }

    @Override
    public void onDoorStateChanged(boolean isDoorOpen) {
        if(isDoorOpen)
        {
            mLogger.i("door open");
        }
        else
        {
            mLogger.i("door close");
            runOnUiThread(() -> {
                cleanUp();
                Intent intent = new Intent(ManagerActivity.this, MainActivity.class);
                startActivity(intent);
                ManagerActivity.this.finish();
            });
        }
    }
}
